# coding=utf-8
# sqlserver的连接
import pymssql
from .config import DatabaseConfig


class MSSQL:
    def __init__(self, host=None, user=None, pwd=None, db=None, port=None):
        # 如果没有提供参数，从配置文件加载
        if host is None:
            config = DatabaseConfig.get_mssql_config()
            self.host = config['host']
            self.user = config['user']
            self.pwd = config['pwd']
            self.db = config['db']
            self.port = config['port']
        else:
            self.host = host
            self.user = user
            self.pwd = pwd
            self.db = db
            self.port = port or 1433

    def __GetConnect(self):
        """
        得到连接信息
        返回: conn.cursor()
        """
        if not self.db:
            raise (NameError, "没有设置数据库信息")
        self.conn = pymssql.connect(host=self.host, port=self.port, user=self.user, password=self.pwd, database=self.db, charset="utf8", autocommit=True)
        cur = self.conn.cursor()
        if not cur:
            raise (NameError, "连接数据库失败")
        else:
            return cur

    def ExecQuery(self, sql, params=None):
        """
        执行查询语句
        返回的是一个包含tuple的list，list的元素是记录行，tuple的元素是每行记录的字段

        """
        cur = self.__GetConnect()
        if params:
            cur.execute(sql, params)
        else:
            cur.execute(sql)
        resList = cur.fetchall()

        # 查询完毕后必须关闭连接
        self.conn.close()
        return resList

    def ExecNonQuery(self, sql, params=None):
        """
        执行非查询语句

        调用示例：
            cur = self.__GetConnect()
            cur.execute(sql, params)
            self.conn.commit()
            self.conn.close()
        """
        cur = self.__GetConnect()
        if params:
            cur.execute(sql, params)
        else:
            cur.execute(sql)
        self.conn.commit()
        self.conn.close()
